﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Callback
{
    public class CallbackHelper<TBook>
    {
        private Dictionary<string, CallbackInfo<TBook>> Callbacks { get; set; } // 注册的回调函数

        public CallbackHelper()
        {
            Callbacks = new Dictionary<string, CallbackInfo<TBook>>();
        }

        public void Subscribe(string subscribeName, object obj, Action<TBook, object> callback)
        {
            if (!Callbacks.ContainsKey(subscribeName))
            {
                Callbacks.Add(subscribeName, new CallbackInfo<TBook>
                {
                    Name = subscribeName,
                    Obj = obj,
                    Callback = callback
                });
            }
        }

        public void CancelSubscribe(string subscribeName)
        {
            if (Callbacks.ContainsKey(subscribeName))
            {
                Callbacks.Remove(subscribeName);
            }
        }

        public void Publish(TBook book)
        {
            foreach (var k in Callbacks)
            {
                k.Value.Callback(book, k.Value.Obj);
            }
        }
    }

    /// <summary>
    /// 回调信息类
    /// </summary>
    class CallbackInfo<T>
    {
        public string Name { get; set; }
        public object Obj { get; set; }
        public Action<T, object> Callback { get; set; }
    }
}
